package com.clwl.supervise.superviseapp.service.investigation;


import cn.hutool.core.date.DateUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.CommonSearchEntity;
import com.clwl.supervise.superviseapp.entity.base.SysDictData;
import com.clwl.supervise.superviseapp.entity.base.SysFile;
import com.clwl.supervise.superviseapp.entity.supervise.*;
import com.clwl.supervise.superviseapp.mapper.base.SysDictDataMapper;
import com.clwl.supervise.superviseapp.mapper.base.SysFileMapper;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.dsj.CasePushMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.util.CompanyProcessUtil;
import com.clwl.supervise.superviseapp.util.UserHelper;
import com.clwl.supervise.superviseapp.util.baiduAPI.BaiduAipUtil;
import com.clwl.supervise.superviseapp.util.file.FileResultEntity;
import com.clwl.supervise.superviseapp.util.file.FileUploadEnum;
import com.clwl.supervise.superviseapp.util.file.FileUploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class InvestigationService {

    @Resource
    private JgInvestigationMapper jgInvestigationMapper;

    @Resource
    private JgInvestigationContentMapper jgInvestigationContentMapper;


    @Resource
    private SysDictDataMapper sysDictDataMapper;

    @Resource
    private JgDocTemplateMapper docTemplateMapper;

    @Resource
    private JgDocTemplateParamMapper docTemplateParamMapper;


    @Resource
    private TcCompanyMapper companyMapper;;


    @Resource
    private BangbanWenshuInfoMapper bangbanWenshuInfoMapper;;


    @Resource
    private BangbanWenshuFileMapper bangbanWenshuFileMapper;

    @Resource
    private TsLawsClauseMapper lawsClauseMapper;

    @Resource
    private TsLawsRegulationsMapper lawsRegulationsMapper;


    @Resource
    private SysFileMapper sysFileMapper;

    @Resource
    private JgDailyCheckMapper dailyCheckMapper;
    @Resource
    private JgDailyContentMapper dailyContentMapper;

    @Resource
    private CasePushMapper casePushMapper;
    /**
     * 获取调查处理列表信息
     * @param pageNum 当前页数
     * @param pageSize 每页数据数量
     * @return
     */
    public IPage<Map<String, Object>> selectInvestigationPage(Integer pageNum, Integer pageSize, CommonSearchEntity commonSearchEntity) {
        commonSearchEntity.setUserId(UserHelper.getUserId());
        commonSearchEntity.setDataRange(UserHelper.getUserInfo().getDataRange());
        commonSearchEntity.setDeptId(UserHelper.getUserInfo().getDeptId());
        List<String> processList = CompanyProcessUtil.getUserProcessList();
        commonSearchEntity.setProcessList(processList);
        Page<Map<String, Object>> iPage = Page.of(pageNum, pageSize);
        iPage.setOptimizeCountSql(false);
        iPage.setSearchCount(false);
        IPage<Map<String,Object>> pageList = jgInvestigationMapper.selectInvestigationPage(iPage,commonSearchEntity);
        for (Map<String, Object> record : pageList.getRecords()) {
            //获取业态信息
            Map<String,Object> companyInfo =  companyMapper.selectBusinessFormatById(record.get("COMPANY_ID"));
            record.put("BUSINESS_TYPE",companyInfo.get("BUSINESS_TYPE"));
            record.put("BUSINESS_TYPE_TWO",companyInfo.get("BUSINESS_TYPE_TWO"));
        }
        return pageList;
    }

    /**
     * 获取调查处理中的问题项
     * @param investigationId 调查处理ID
     * @return
     */
    public List<Map<String, Object>> getProblemList(Long investigationId) {
        return jgInvestigationContentMapper.selectProblemList(investigationId);
    }

    /**
     * 上传立案审批表文件
     * @param investigationId 调查处理ID
     * @param file 文件
     * @param type 文件类型：1-立案审批表；2-决定书；3-不予立案审批表;4-不予立案的情况说明文件
     * @return
     */
    public Map<String,Object> uploadInvestigationFile(Long investigationId, MultipartFile file, String type) {
        Map<String,Object>  resultMap = new HashMap<>();
        JgInvestigation investigation = jgInvestigationMapper.selectById(investigationId);
        if(investigation == null){
            throw new RuntimeException("调查处理信息未找到");
        }
        FileResultEntity fileUrl = null;
        try {
            fileUrl = FileUploadUtil.uploadFile(file, FileUploadEnum.investigation.getPath());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传文件失败");
        }
        switch (type){
            case "1":
                investigation.setFilingApprovalUrl(fileUrl.getFilePath());
                break;
            case "2":
                investigation.setDecisionLetterUrl(fileUrl.getFilePath());
                break;
            case "3":
                investigation.setNotFilingApprovalUrl(fileUrl.getFilePath());
                break;
            case "4":
                investigation.setNotFilingDescription(fileUrl.getFilePath());
                break;
        }

        try {
            jgInvestigationMapper.updateById(investigation);
            resultMap.put("fileUrl",fileUrl.getFilePath());
            resultMap.put("fileName",fileUrl.getFileName());
            String audioUrl = BaiduAipUtil.updateSpotImage(file);
            org.json.JSONArray resultJSONArray = BaiduAipUtil.textSpot(audioUrl);
            BaiduAipUtil.deleteSpotImage(audioUrl);
            if (resultJSONArray != null) {
                String penaltyNumber = ""; //处罚编号
                String party = ""; //当事人
                String penalties = ""; // 处罚事项
                String dateOfPenalty = ""; //生效日期
              //  StringBuffer s = new StringBuffer();
                for (int i = 0; i < resultJSONArray.length(); i++) {
                    if(i == 2){
                        penaltyNumber = resultJSONArray.getJSONObject(i).getString("words");
                    }
                    if(i == 3){
                        party = resultJSONArray.getJSONObject(i).getString("words");
                    }
                    if(i >= 26 && i <= 50){
                        penalties = penalties + resultJSONArray.getJSONObject(i).getString("words");
                    }
                    if(i == 53){
                        dateOfPenalty =  resultJSONArray.getJSONObject(i).getString("words");
                    }
                   // s.append(resultJSONArray.getJSONObject(i).getString("words"));
                }
                resultMap.put("penaltyNumber", penaltyNumber);//识别结果
                resultMap.put("party", party);//识别结果
                resultMap.put("penalties", penalties );//识别结果
                resultMap.put("dateOfPenalty", dateOfPenalty);//识别结果
            }
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("调查处理信息保存失败");
        }
    }


    /**
     * 获取调查处理中处选择不立案的时候不予立案的理由选项
     * @return
     */
    public List<SysDictData> notFilingList() {
            return sysDictDataMapper.selectByDictTypeCode("no_filing_reason");
    }

    /**
     * 保存调查处理信息
     * @param investigationId
     * @param filing 是否立案；1-立案。2-不立案
     * @param temporary 是否临时保存；1-临时。2-不临时
     * @param noFilingReason 不予立案的理由
     * @return
     */
    public void saveInvestigationInfo(Long investigationId, String filing, String temporary,String noFilingReason) {
        JgInvestigation investigation = jgInvestigationMapper.selectById(investigationId);
        if(investigation == null){
            throw new RuntimeException("调查处理信息未找到");
        }
        investigation.setCheckResult(filing);
        investigation.setCheckPersonnel(UserHelper.getUserId());
        investigation.setCheckPersonnelName(UserHelper.getUserInfo().getName());
        investigation.setUpdateTime(new Date());
        investigation.setUpdateUserId(UserHelper.getUserId());
        investigation.setUpdateUserName(UserHelper.getUserInfo().getName());
        if ("2".equals(temporary)){
            investigation.setCheckTime(DateUtil.format(new Date(),"yyyy-MM-dd"));
            investigation.setCheckStatus("2");
        }
        if("2".equals(filing) && StringUtils.isBlank(noFilingReason)){
            throw new RuntimeException("请传递不予立案理由信息");
        }
        investigation.setNotFilingCase(noFilingReason);
        jgInvestigationMapper.updateById(investigation);
    }


    /**
     * 查询已经处理完成的调查处理信息
     * @param investigationId 调查处理id
     * @return
     */
    public JgInvestigation getInvestigationInfo(Long investigationId) {
        JgInvestigation investigation = jgInvestigationMapper.selectById(investigationId);
        List<JgInvestigationContent> investigationContentList =  jgInvestigationContentMapper.selectByInvestigationId(investigationId);
        investigation.setInvestigationContentList(investigationContentList);
        return investigation;
    }

    /**
     * 获取模板列表
     * @param templateType 模板类型
     * @return
     */
    public List<JgDocTemplate> getTemplateList(String templateType) {
        QueryWrapper<JgDocTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DELETE_FLAG","0");
        if(StringUtils.isNotBlank(templateType)) {
            queryWrapper.eq("TEMPLATE_TYPE", templateType);
        }
        queryWrapper.orderByDesc("CREATE_TIME");
        return   docTemplateMapper.selectList(queryWrapper);
    }

    /**
     * 获取文书模板需要填写的内容
     * @param templateId 模板ID
     * @param investigationId 调查处理ID
     * @return
     */
    public List<Map<String, Object>> getTemplateInputList(Long templateId,Long investigationId)   {
        JgDocTemplate docTemplate = docTemplateMapper.selectById(templateId);
        String templateContent =  docTemplate.getTemplateContent();
        log.info("文本内容:{}",templateContent);
        List<Map<String, Object>> result = new ArrayList<>();
        Pattern pattern = Pattern.compile("\\$\\{(.*?)}");
        Matcher matcher = pattern.matcher(templateContent);
        List<String> codeList = new ArrayList<>();
        //分析文本中需要填写的code
        while (matcher.find()) {
            String code = matcher.group(1);
           codeList.add(code);
        }
        //去重
        codeList = codeList.stream().distinct().collect(Collectors.toList());
        for (String code : codeList) {
            Map<String, Object> queryValue = new HashMap<>();
            JgDocTemplateParam templateParam  = docTemplateParamMapper.selectByCode(code,templateId);
            if(templateParam == null){
                continue;
            }
            queryValue.put("type", templateParam.getType());
            queryValue.put("name", templateParam.getName());
            queryValue.put("code", templateParam.getCode());
            if(StringUtils.isNoneBlank(templateParam.getQuerySql())) {
                Map<String, Object> resultMap = docTemplateParamMapper.selectResult(templateParam.getQuerySql(), investigationId);
                log.info("查询结果:{}",resultMap);
                queryValue.put("value",resultMap == null ? "" : resultMap.get("VALUE"));
            } else {
                queryValue.put("value", "");
            }
            log.info("queryValue:{}",queryValue);
            result.add(queryValue);
        }
        log.info("匹配结果:{}",result);
        return result;
    }

    /**
     * 生成模板内容
     * @param templateId 模板id
     * @param parameterMap 参数
     * @return
     */
    public String generatorDocument(Long templateId, Map<String, Object> parameterMap) {
        JgDocTemplate docTemplate = docTemplateMapper.selectById(templateId);
        String templateContent =  docTemplate.getTemplateContent();
        log.info("文本内容:{}",templateContent);
        Set<String> keySet = parameterMap.keySet();
        for (String key : keySet) {
            templateContent = templateContent.replaceAll("\\$\\{"+key+"\\}",parameterMap.get(key)+"");
        }
        log.info("替换完成文本内容:{}",templateContent);
        return templateContent;
    }

    /**
     * 生成模板字段帮办
     * @param code 需要帮办的编码
     * @param investigationId 调查处理id
     * @param templateId 模板id
     * @return
     */
    @PostMapping("fieldHelp")
    public BangbanWenshuInfo getFieldHelp(String code, Long investigationId, Long templateId) {
        QueryWrapper<BangbanWenshuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("WSID",templateId);
        queryWrapper.eq("CODE",code);
        BangbanWenshuInfo wenshuInfo = bangbanWenshuInfoMapper.selectOne(queryWrapper);
        if(wenshuInfo == null){
            wenshuInfo = new BangbanWenshuInfo();
        }
        StringBuffer stringBuffer = new StringBuffer();
        if(investigationId != null){
            //如果检查处理id不为空，则针对调查处理id查询此项自动填充内容
            JgDocTemplateParam templateParam  = docTemplateParamMapper.selectByCode(code,templateId);
            if(StringUtils.isNoneBlank(templateParam.getQuerySql())) {
                Map<String, Object> resultMap = docTemplateParamMapper.selectResult(templateParam.getQuerySql(), investigationId);
                log.info("查询结果:{}",resultMap);
                stringBuffer.append("该企业的");
                stringBuffer.append(templateParam.getName());
                stringBuffer.append("为：");
                stringBuffer.append(resultMap == null ? "" : resultMap.get("VALUE"));
            }
        }
        stringBuffer.append("\t");
        stringBuffer.append(wenshuInfo.getQtbb());
        wenshuInfo.setQtbb(stringBuffer.toString());
        if(StringUtils.isNotBlank(wenshuInfo.getId())) {
            //帮办文件列表
            QueryWrapper<BangbanWenshuFile> wenshuFileQueryWrapper = new QueryWrapper<>();
            wenshuFileQueryWrapper.eq("INFO_ID",wenshuInfo.getId());
            List<BangbanWenshuFile> fileList = bangbanWenshuFileMapper.selectList(wenshuFileQueryWrapper);
            for (BangbanWenshuFile bangbanWenshuFile : fileList) {
                SysFile sysFile = sysFileMapper.selectById(bangbanWenshuFile.getFileId());
                if(sysFile == null){
                    continue;
                }
                bangbanWenshuFile.setFilePath(sysFile.getFilePath());
            }
            wenshuInfo.setBangbanWenshuFileList(fileList);
        }
        //依据法律法规
        StringBuffer fcfg = new StringBuffer();
        if(wenshuInfo.getFvfg() != null){
            TsLawsClause lawsClause = lawsClauseMapper.selectById(wenshuInfo.getFvfg());
                fcfg.append("依据");
            if(lawsClause != null){
                //获取法律法依据
                TsLawsRegulations lawsRegulations = lawsRegulationsMapper.selectById(lawsClause.getLawsRegulationsId());
                fcfg.append(lawsRegulations.getName());
                fcfg.append("中的");

            }
            fcfg.append(lawsClause.getContent());
        }
        wenshuInfo.setFvfgtxt(fcfg.toString());
        return  wenshuInfo;
    }

    /**
     * 文书帮办查询
     * @param investigationId 调查处理id
     * @param templateId 模板id
     * @return
     */
    public Map<String, Object> documentHelp(Long investigationId, Long templateId) {
        Map<String, Object> result = new HashMap<>();
        JgInvestigation investigation = jgInvestigationMapper.selectById(investigationId);
        //首次检查不合格原因
        JgDailyCheck lastNoQualifiedDailyCheck = dailyCheckMapper.selectLastNoQualifiedDailyByCompanyId(investigation.getCompanyId());
        if(lastNoQualifiedDailyCheck != null) {
            List<Map<String, Object>> contentList = dailyContentMapper.selectByDailyCheckId(lastNoQualifiedDailyCheck.getId());
            Stream<Map<String, Object>> noQualifiedList = contentList.stream().filter(predicate -> {
                return StringUtils.equals(predicate.get("SELECTION").toString(), "2");
            });
            List<Map<String, Object>> list = noQualifiedList.collect(Collectors.toList());

            result.put("unqualified_reason", list);
        }
        //本次检查人工智能处罚意见
        //todo 等大数据
        result.put("punishment_opinions","根据情情况可进行处罚1000元");

        //历史执法记录
        List<JgDailyCheck> dailyCheckList = dailyCheckMapper.selectRealyByCompanyId(investigation.getCompanyId(),5);
        result.put("enforcement_records",dailyCheckList);
        //历史执法案例
        //todo 等大数据
//        List<Map<String,Object>> caselist= new ArrayList<>();
//        Map<String,Object> caseMap = new HashMap<>();
//        caseMap.put("title"," 洛阳市市场监督管理局、洛阳银都国际饭店有限公司食品药品安全行政管理(食品、药品)再审行政判决书 ");
//        caseMap.put("content","<div data-v-218d74ae=\"\" class=\"Historical\"><span data-v-218d74ae=\"\"> 洛阳市市场监督管理局、洛阳银都国际饭店有限公司食品药品安全行政管理(食品、药品)再审行政判决书 </span><div data-v-218d74ae=\"\" class=\"Penalty\"></div><p data-v-218d74ae=\"\" class=\"c-box\"></p><div data-v-218d74ae=\"\" class=\"title-name\">胜诉单位:</div><div data-v-218d74ae=\"\" class=\"dec-text\">洛阳市市场监督管理局 诉讼请求</div><p data-v-218d74ae=\"\"></p><p data-v-218d74ae=\"\" class=\"c-box\"></p><div data-v-218d74ae=\"\" class=\"title-name\">诉讼请求:</div><div data-v-218d74ae=\"\" class=\"dec-text\">不服河南省洛阳市中级人民法院(2019)豫03行终203号行政判决向本院申请再审</div><p data-v-218d74ae=\"\"></p><p data-v-218d74ae=\"\" class=\"c-box\"></p><div data-v-218d74ae=\"\" class=\"title-name\">行政处罚:</div><div data-v-218d74ae=\"\" class=\"dec-text\">1没收违法所得30元:2 并处罚款50000元。都饭店于2018年7月25日签收该行政处罚决定书，并干同年8月9日缴纳上述罚没款50030元罚行为，向河南省洛阳市西工区人民法院提起诉讼事实经过:因银都饭店早餐经营的小油条数量不够一审判决:驳回银都饭店的诉讼请求。一审案件受理费50元，由铂都饭店负担二审判决:一、撤销河南省洛阳市西工区人民法院(2019)豫0303行初3号行政判决二、撤销洛阳市场监管局(洛)食药监食罚[2018]9号行政处罚决定二审案件受理费共计100元，由洛阳市场监管局承担。 </div><p data-v-218d74ae=\"\"></p></div>");
//        caselist.add(caseMap);
//        List<Map<String,Object>> caselist = this.casePush(null);
//        result.put("law_enforcement_cases",caselist);

        return result;
    }
    
    @DS("ads")
    public List<Map<String,Object>> casePush(String cause){
    	List<Map<String,Object>> caselist= this.casePushMapper.casePush(cause);
    	return caselist;
    }
}
